﻿using GateWayCommonService.Device;
using Iot.Device.Pn532;
using IotDeviceToolHepler;
using IotDeviceToolHepler.Device;
using IotDeviceToolHepler.Model.Device;
using Microsoft.EntityFrameworkCore.Metadata;
using Models.Common;
using Models.Device;
using MySqlX.XDevAPI.Common;
using Nancy.Json;
using NetTaste;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Data;
using System.Device.I2c;
using System.Text;
using System.Threading;
using Utils_Base;
using Utils_ORM;
using Utils_ORM.MySql_IotWork;
using static Models.Common.EnumDeviceState;

namespace GateWayCommonService.GateWay
{
    /// <summary>
    /// 处理指令
    /// </summary>
    public class ServiceHandleCommand
    {

        //内存保存设备执行次数
        static List<ModelHandleEventList> handleEventLists = new List<ModelHandleEventList>();
        /// <summary>
        /// 判断执行次数
        /// </summary>
        /// <param name="obj"></param>
        public void handle(object obj)
        {



            //判断执行次数，用于传感器，连续上传
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGateWayData;
            if (commandLogModel.repeatCount == -100)
            {
                //停止
                List<ModelHandleEventList> handleEventList = handleEventLists.Where(c => c.d_guid == commandLogModel.d_guid && c.key == commandLogModel.key).ToList();
                foreach (ModelHandleEventList item in handleEventList)
                {
                    item.repeatCount = -100;
                    handleEventLists.Remove(item);
                }


                //回传成功
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.respMsg = ResponseCode.SUCCESS_MSG;
                new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                return;
            }
            else
            {
                handle_action(obj);//执行
                //return;
                //下面重复执行
                if (commandLogModel.repeatCount == -1 || commandLogModel.repeatCount > 1)
                {
                    ModelHandleEventList handleEvent = new ModelHandleEventList();
                    handleEvent.d_guid = commandLogModel.d_guid;
                    handleEvent.repeatCount = commandLogModel.repeatCount;
                    handleEvent.key = commandLogModel.key;
                    handleEventLists.Add(handleEvent);
                }
                else
                {
                    return;
                }
            }
            //是否重复执行
            int repeatCount = 0;
            while (true)
            {

                ModelHandleEventList doEvent = handleEventLists.Where(c => c.d_guid == commandLogModel.d_guid && c.key == commandLogModel.key).FirstOrDefault();
                if (doEvent == null)
                {
                    break;
                }

                repeatCount = repeatCount + 1;
                int limitRepeatCount = doEvent.repeatCount;

                if (limitRepeatCount == -100)
                {//如果非-1无限次数，判断执行次数，并退出
                    break;
                }

                if (limitRepeatCount != -1 && repeatCount >= limitRepeatCount)
                {//如果非-1无限次数，判断执行次数，并退出
                    break;
                }
                if (commandLogModel.repeatCountInterval > 0)
                {//设置心跳时间
                    Thread.Sleep(commandLogModel.repeatCountInterval);
                }
                else
                {
                    //默认1秒
                    Thread.Sleep(1000);
                }

                Console.WriteLine(commandLogModel.device_remark + ".....重复执行 start.....count:" + repeatCount + "---" + limitRepeatCount);
                handle_action(obj);//执行
                Console.WriteLine(commandLogModel.device_remark + ".....重复执行 end......count:" + repeatCount + "---" + limitRepeatCount);


            }
        }



        public void handle_action(object obj)
        {
            try
            {
                MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;

                CommandLogModel item = mQReqModel.toGateWayData;

                if (item.deviceModelCode == "1001")
                {
                    Console.WriteLine(".....获得能力Sht30_I2C.....");
                    //获得能力，开始推送数据
                    ServiceGpio.gateWayExecuteCommand(mQReqModel);
                }
                else if (item.deviceModelCode == "1004")
                {
                    Console.WriteLine(".....获得能力Sht30_I2C.....");
                    //获得能力，开始推送数据
                    new ServiceSensorSHT301004().gateWayExecuteCommand(mQReqModel);
                }
                else if (item.agreementType == EnumAgreementType.RS485)
                {
                    Console.WriteLine(".....RS485.....");
                    new ServiceHandleRS485().gateWayExecuteRS485(mQReqModel);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }




        public void handleError(object obj)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGateWayData;
            ModelReceverData modelDeviceData = new ModelReceverData();
            modelDeviceData.content = "不被支持的指令";
            mQReqModel.respCode = ResponseCode.System_ERROR;
            mQReqModel.respMsg = MQEventEnum.Event_State_Error;
            mQReqModel.toServerData = modelDeviceData;
            new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
        }
    }

}
